package com.example.elderlycare.utils;

import com.example.elderlycare.config.ZhenziSmsConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhenzi.sms.ZhenziSmsClient;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Component
public class ZhenziSms {
    @Resource
    private ZhenziSmsConfig zhenziSmsConfig;

    private ZhenziSmsClient client;

    @Bean
    public ZhenziSmsClient initSms() {
        if (client == null) {
            client = new ZhenziSmsClient(zhenziSmsConfig.getApiUrl(),
                    zhenziSmsConfig.getAppId(), zhenziSmsConfig.getAppSecret());
            return client;
        }
        return client;
    }

    /**
     * 获取当前账号可发验证码的条数
     *
     * @return 当前账号可发验证码的条数
     */
    public Integer checkBalance() {
        try {
            String balance = client.balance();
            ObjectMapper objectMapper = new ObjectMapper();
            Result result = objectMapper.readValue(balance, Result.class);
            return (int) result.getData();
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 发送验证码
     *
     * @param phoneNumber      手机号码
     * @param verificationCode 验证码
     * @return 是否成功布尔值
     */
    public boolean sendMessage(String phoneNumber, String verificationCode) {
        try {
            Map<String, Object> params = new HashMap<>(3);
            params.put("number", phoneNumber);
            String[] templateParams = new String[2];
            templateParams[0] = verificationCode;
            /*设置有效时间，单位为分钟*/
            templateParams[1] = String.valueOf(zhenziSmsConfig.getTimeOut());
            params.put("templateParams", templateParams);
            params.put("templateId", zhenziSmsConfig.getTemplateId());
            String response = client.send(params);
            ObjectMapper objectMapper = new ObjectMapper();
            Result success = objectMapper.readValue(response, Result.class);
            return success.getCode() == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Data
    static class Result implements Serializable {
        private Integer code;
        private Object data;
    }
}
